package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomizeExceptionBuilder;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.ApUserLoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.vos.ApUserLoginVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.IApUserService;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ApUserService extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    /**
     * APP 端用户登录业务 API 实现
     * @param apUserLoginDTO
     * @return
     */
    @Override
    public ResponseResult login(ApUserLoginDTO apUserLoginDTO) {
            Map<String, Object> result = new HashMap<>();
        //1.校验参数
            //1.1校验硬件设备号
        if(apUserLoginDTO.getEquipmentId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
            //1.2校验手机号和密码
        if(StringUtils.isNotBlank(apUserLoginDTO.getPhone()) && StringUtils.isNotBlank(apUserLoginDTO.getPassword())){
            //2.1使用手机号和密码进行登录
            ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, apUserLoginDTO.getPhone()));
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "当前手机号未绑定任何账号，请先注册");
            }
            if(apUser.getStatus()){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "当前账号已被锁定，请联系管理员");
            }
            String digestPassword = DigestUtils.md5DigestAsHex((apUserLoginDTO.getPassword() + apUser.getSalt()).getBytes());
            if(!digestPassword.equals(apUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "登录密码错误，请重新登录");
            }
            //3.颁发 token
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            //4.返回响应
            ApUserLoginVO apUserLoginVO = new ApUserLoginVO();
            BeanUtils.copyProperties(apUser, apUserLoginVO);
            result.put("token", token);
            result.put("user", apUserLoginVO);
            return ResponseResult.okResult(result);
        }else{
            //2.2使用硬件设备号进行登录
            result.put("token", AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(result);
        }
    }
}
